/**
 *@category 
 *@author 邱磊
 *@date 2015年11月13日 下午1:14:07
 */
package com.hsnn.medstgmini.sys.dao.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.sys.dao.SysImportFileInfoDao;
import com.hsnn.medstgmini.sys.model.form.SysImportFileInfoForm;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;

/**
 *@category 
 *@author 邱磊
 *@date 2015年11月13日 下午1:14:07
 *@param 
 */
@Repository
public class SysImportFileInfoDaoImpl implements SysImportFileInfoDao {
	@Autowired
	private HibernateSqlUtil dao;
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	private Session getSession() {
		Session session = sessionFactory.getCurrentSession();
		if (null == session) {
			session = sessionFactory.openSession();
		}
		return session;
	}
	/**
	 * 
	 *@category 新增文件上传记录
	 *@author 邱磊
	 *@date 2015年11月13日 下午1:19:22
	 *@param
	 */
	public void addImportFile(SysImportFileInfoForm form){
		StringBuffer sql = new StringBuffer()
		.append("insert into sys_import_file_info ")
		.append("(id,file_name,file_orginal_name,proj_id,file_type,user_id,upload_datetime,file_path,check_file_path,status,upd_user,upd_datetime)")
		.append(" values")
		.append(" (:id,:fileName,:fileOrginalName,:projId,:fileType,:userId,SYSDATE(),:filePath,:checkFilePath,0,:updUser,SYSDATE())");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", form.getId());
		params.put("fileName", form.getFileName());
		params.put("fileOrginalName", form.getFileOrginalName());
		params.put("projId", form.getProjId());
		params.put("fileType", form.getFileType());
		params.put("userId", form.getUserId());
		params.put("filePath", form.getFilePath());
		params.put("checkFilePath", form.getCheckFilePath());
		params.put("updUser", form.getUpdUser());
		dao.executeSql(sql.toString(), params);
	}
	/**
	 * 
	 *@category 获取文件列表数据
	 *@author 邱磊
	 *@date 2015年11月13日 下午2:02:14
	 *@param 
	 *@return Pagination
	 */
	public Pagination getImportFileDataList(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append("select a.id as fileId, a.file_orginal_name as fileName, a.proj_id, ")
		.append("b.name as upUser, a.upload_datetime as upTime,a.status ")
		.append(" from sys_import_file_info a")
		.append(" left join sys_user b on a.user_id=b.id")
		.append(" where a.file_type=:fileType ");
		StringBuffer countsql = new StringBuffer()
		.append("select count(*) from sys_import_file_info a")
		.append(" where a.file_type=:fileType ");
		Map<String, String> map = page.getConditions();
		if (StringUtils.isNotBlank(map.get("projId"))){
			sql.append(" and a.proj_id= :projId");
			countsql.append(" and a.proj_id= :projId");
		}
		if (StringUtils.isNotBlank(map.get("fileName"))){
			sql.append(" and a.file_orginal_name like :fileName");
			countsql.append(" and a.file_orginal_name like :fileName");
		}
		if (StringUtils.isNotBlank(map.get("starttime"))){
			sql.append(" and DATE_FORMAT(a.upload_datetime,'%Y-%m-%d') >= :starttime");
			countsql.append(" and DATE_FORMAT(a.upload_datetime,'%Y-%m-%d') >= :starttime");
		}
		if (StringUtils.isNotBlank(map.get("endtime"))){
			sql.append(" and DATE_FORMAT(a.upload_datetime,'%Y-%m-%d') <= :endtime");
			countsql.append(" and DATE_FORMAT(a.upload_datetime,'%Y-%m-%d') <= :endtime");
		}
		if (StringUtils.isNotBlank(map.get("status"))){
			sql.append(" and a.status = :status");
			countsql.append(" and a.status = :status");
		}
		sql.append(" order by a.upload_datetime desc");
		Query query = getSession().createSQLQuery(sql.toString()).setCacheable(true);
		Query countQuery = getSession().createSQLQuery(countsql.toString());
		query.setInteger("fileType", ParseNumber.toInteger(map.get("filetype")));
		countQuery.setInteger("fileType", ParseNumber.toInteger(map.get("filetype")));
		if (StringUtils.isNotBlank(map.get("projId"))){
			query.setString("projId", map.get("projId"));
			countQuery.setString("projId", map.get("projId"));
		}
		if (StringUtils.isNotBlank(map.get("fileName"))){
			query.setString("fileName", "%" + map.get("fileName") + "%");
			countQuery.setString("fileName", "%" + map.get("fileName") + "%");
		}
		if (StringUtils.isNotBlank(map.get("starttime"))){
			query.setString("starttime", map.get("starttime"));
			countQuery.setString("starttime", map.get("starttime"));
		}
		if (StringUtils.isNotBlank(map.get("endtime"))){
			query.setString("endtime", map.get("endtime"));
			countQuery.setString("endtime", map.get("endtime"));
		}
		if (StringUtils.isNotBlank(map.get("status"))){
			query.setInteger("status", ParseNumber.toInteger(map.get("status")));
			countQuery.setInteger("status", ParseNumber.toInteger(map.get("status")));
		}
		countQuery.setCacheable(true);
		BigInteger records = (BigInteger) countQuery.uniqueResult();
		page.setRecords(records.longValue());
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<?> list = query.list();
		page.setRows(list);
		return page;
	}
	/**
	 * 
	 *@category 根据文件ID更新文件状态
	 *@author 邱磊
	 *@date 2015年11月13日 下午2:33:56
	 *@param 
	 *@return void
	 */
	public void updateImportFileStatus(int status,String fileId){
		Session session = sessionFactory.openSession();
		String sql = "UPDATE sys_import_file_info set status=:status where id=:fileId";
		Query aquery = session.createSQLQuery(sql.toString());
		aquery.setParameter("status", status);
		aquery.setParameter("fileId", fileId);
		aquery.executeUpdate();
		session.clear();
		session.close();
	}
	/**
	 * 
	 *@category 根据文件ID获取文件信息
	 *@author 邱磊
	 *@date 2015年11月13日 下午2:44:24
	 *@param 
	 *@return Map<String,Object>
	 */
	public Map<String, Object> getImportFileById(String fileId){
		Session session = sessionFactory.openSession();
		String sql = "select * from sys_import_file_info t where t.id=:fileId";
		Query query = session.createSQLQuery(sql.toString());
		query.setString("fileId", fileId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<Map<String, Object>> list = query.list();
		session.clear();
		session.close();
		if (null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
}
